<template>
  <div class="screen-container">
    <canvas id="canvasSave2"></canvas>
  </div>
</template>

<script>
import {
  getPolygonDimensions,
  resizeCallback,
  isPointInPolygon,
} from '@/utils/canvas'
export default {
  data() {
    return {
      canSave: null,
      ctxSave: null,
      data: [],
      colorArr: ['#e60013', '#fff100', '#e5803c', '#4978b0'],
    }
  },
  mounted() {
    this.canSave = document.getElementById('canvasSave2')
    this.ctxSave = this.canSave.getContext('2d')
    this.ctxSave.strokeStyle = 'rgba(59, 50, 40,1)' //线条颜色
    this.ctxSave.lineWidth = 1 //线条粗细
    const arr = window.localStorage.getItem('test') || ''
    console.log(arr)
    if (arr) {
      this.data = JSON.parse(arr)
      this.init()
    }
    this.canSave.addEventListener('click', this.handleCanvasClick)
    window.addEventListener('resize', resizeCallback(1280, 608))
    // 添加点击事件监听器
    resizeCallback(1280, 608)
  },
  methods: {
    handleCanvasClick(event) {
      const rect = this.canSave.getBoundingClientRect()
      const x = event.clientX - rect.left
      const y = event.clientY - rect.top
      this.data.forEach((item) => {
        if (isPointInPolygon({ x, y }, item.ponitArr)) {
          alert('点击了区域：' + item.houseName)
        }
      })
    },
    // 回显数据
    init() {
      this.data.map((item) => {
        this.canvasFill(item.ponitArr, item.color, item.houseName)
      })
    },
    //回显canvas区域
    canvasFill(pointArr, color, houseName) {
      this.ctxSave.clearRect(0, 0, this.ctxSave.width, this.ctxSave.height)
      this.ctxSave.beginPath()
      if (pointArr.length > 1) {
        this.ctxSave.moveTo(pointArr[0].x, pointArr[0].y)
        for (var i = 1; i < pointArr.length; i++) {
          this.ctxSave.lineTo(pointArr[i].x, pointArr[i].y)
        }
        this.ctxSave.fillStyle = color + 'B3' //填充颜色
        this.ctxSave.fill()
        this.ctxSave.stroke() //绘制

        const dimensions = getPolygonDimensions(pointArr)
        this.canvasText(
          houseName,
          { x: dimensions.minX, y: dimensions.minY },
          dimensions
        )
      }
    },
    //绘制文字
    canvasText(text, point, dimensions) {
      this.ctxSave.textAlign = 'center' //设置文本对齐方式
      this.ctxSave.textBaseline = 'middle' //文本基线

      this.ctxSave.fillStyle = '#000' //字体颜色
      this.ctxSave.font = 'italic bold 16px Arial' // 设置字体样式、粗细和大小
      const x = point.x + dimensions.width / 2
      const y = point.y + dimensions.height / 2
      this.ctxSave.fillText(text, x, y) //绘制文字
    },
  },
}
</script>

<style scoped>
.screen-container {
  width: 100%;
  height: 100%;
}

#canvasSave2 {
  width: 100%;
  height: 100%;
  background: url('@/assets/table.jpg') no-repeat center;
  background-size: cover;
  border: 1px solid red;
}
</style>
